package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserAuth;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 登录接口
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<UserVo> login(LoginDto dto) {
        //2.实例化用户和密码封装对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(
                dto.getUsername(),dto.getPassword()
        );
        //1.调用认证管理器，获取认证对象
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (ObjectUtil.isEmpty(authenticate)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //3获取用户信息
        UserAuth userAuth= (UserAuth) authenticate.getPrincipal();

        //4.5 数据脱敏
        userAuth.setPassword("*****");


        //获取用户资源列表  --97条 当前用户可以访问的资源
        List<Resource> requestPathList = resourceMapper.findResourceVoListByUserId(Long.valueOf(userAuth.getId()));
        //转化泛型
        List<String> resourcePathList = requestPathList.stream().map(Resource::getRequestPath).collect(Collectors.toList());

        //获取白名单列表  110条，所有的用户都可以访问的资源
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        //两个集合进行合并处理
        resourcePathList.addAll(publicAccessUrls);


        //4.生成token
        Map<String, Object> claims=new HashMap<>();
        claims.put("user", JSONUtil.toJsonStr(userAuth));
        String token = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(),
                claims
        );

        //把resourcePathList存入到redis中

        String accessUrlsCacheKey = UserCacheConstant.ACCESS_URLS_CACHE+userAuth.getId();
        redisTemplate.opsForValue().set(accessUrlsCacheKey,JSONUtil.toJsonStr(resourcePathList),jwtTokenManagerProperties.getTtl(),TimeUnit.HOURS);

        //5.返回数据
        UserVo userVo = BeanUtil.toBean(userAuth, UserVo.class);
        userVo.setUserToken(token);
        return ResponseResult.success(userVo);
    }
}
